/*
const promise = new Promise((resolve,reject)=>{
         reject(1);
});

const promise1 = promise.then(console.log,console.log).catch(e=> console.log(e,2))  //有then会先走then
*/


function Promise(fn){
    this.cbs = [];
    
    const resolve = (value) => {
        setTimeout(()=>{
            this.data = value;
            this.cbs.forEach(cb => cb(value))
        })
    }

    fn(resolve)

}


Promise.prototype.then = function(onResolved){
    
    return new Promise((resolve)=>{
        //.then会立刻执行以下逻辑
        this.cbs.push(()=>{
           const res = onResolved(this.data);
           if(res instanceof Promise){
               res.then(resolve)
           }else{
               resolve(res)
           }
         })
    })
     
}
    


new Promise((resolve) => {
    setTimeout(() => {
      resolve(1);
    }, 500);
})

.then((res) => {
      console.log(res);
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve(2);
        }, 500);
      });
})

.then(console.log);
  


/* 

500ms 后输出 1
500ms 后输出 2 

*/

